package com.dfk.bs.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dfk.bs.common.vo.R;
import com.dfk.bs.entity.admin.Admin;
import com.dfk.bs.service.admin.AdminService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Api("验证码获取")
@CrossOrigin
@Controller
public class AdminLoginController {

    //验证码
    @Autowired
    DefaultKaptcha defaultKaptcha;

    //管理员
    @Autowired
    private AdminService adminService;

    @ApiOperation("获取验证码图片")
    @GetMapping("/captcha.jpg")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, createText);
            String sessionId = httpServletRequest.getSession().getId();
            System.out.println("----------"+sessionId);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
    /**
     * 登录
     */
    @ApiOperation("登录接口")
    @ResponseBody
    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody JSONObject json) {
        String username = json.getString("username");
        String password = json.getString("password");
        String captcha = json.getString("captcha");
        Admin admin=new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        String sessionId = request.getSession().getId();
        System.out.println("======="+sessionId);
        String kaptcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
        if(!captcha.equals(kaptcha)){
            return R.error().message("验证码错误");
        }
        Admin one = adminService.getOne(
                Wrappers.<Admin>lambdaQuery()
                        .eq(Admin::getUsername, username)
                        .eq(Admin::getPassword, password), false
        );
         if (one==null){
             return R.error().message("用户名或密码错误");
         }
        return R.ok().message("登陆成功");

    }

}
